{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h1> 2d. Distributed training and monitoring </h1>\n",
    "\n",
    "In this notebook, we refactor to call ```train_and_evaluate``` instead of hand-coding our ML pipeline. This allows us to carry out evaluation as part of our training loop instead of as a separate step. It also adds in failure-handling that is necessary for distributed training capabilities."
    ]
  },
  {

"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
 "# Ensure the right version of Tensorflow is installed.\n",
 "!pip freeze | grep tensorflow==2.6"
 ]
},
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "import numpy as np\n",
    "import shutil\n",
    "print(tf.__version__)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h2> Input </h2>\n",
    "\n",
    "Read data created in Lab1a, but this time make it more general, so that we are reading in batches.  Instead of using Pandas, we will use Datasets."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "CSV_COLUMNS = ['fare_amount', 'pickuplon','pickuplat','dropofflon','dropofflat','passengers', 'key']\n",
    "LABEL_COLUMN = 'fare_amount'\n",
    "DEFAULTS = [[0.0], [-74.0], [40.0], [-74.0], [40.7], [1.0], ['nokey']]\n",
    "\n",
    "def read_dataset(filename, mode, batch_size = 512):\n",
    "  def _input_fn():\n",
    "    def decode_csv(value_column):\n",
    "      columns = tf.compat.v1.decode_csv(value_column, record_defaults = DEFAULTS)\n",
    "      features = dict(zip(CSV_COLUMNS, columns))\n",
    "      label = features.pop(LABEL_COLUMN)\n",
    "      return features, label\n",
    "    \n",
    "    # Create list of files that match pattern\n",
    "    file_list = tf.compat.v1.gfile.Glob(filename)\n",
    "\n",
    "    # Create dataset from file list\n",
    "    dataset = tf.compat.v1.data.TextLineDataset(file_list).map(decode_csv)\n",
    "    \n",
    "    if mode == tf.estimator.ModeKeys.TRAIN:\n",
    "        num_epochs = None # indefinitely\n",
    "        dataset = dataset.shuffle(buffer_size = 10 * batch_size)\n",
    "    else:\n",
    "        num_epochs = 1 # end-of-input after this\n",
    " \n",
    "    dataset = dataset.repeat(num_epochs).batch(batch_size)\n",
    "    return dataset.make_one_shot_iterator().get_next()\n",
    "  return _input_fn"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h2> Create features out of input data </h2>\n",
    "\n",
    "For now, pass these through.  (same as previous lab)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "INPUT_COLUMNS = [\n",
    "    tf.feature_column.numeric_column('pickuplon'),\n",
    "    tf.feature_column.numeric_column('pickuplat'),\n",
    "    tf.feature_column.numeric_column('dropofflat'),\n",
    "    tf.feature_column.numeric_column('dropofflon'),\n",
    "    tf.feature_column.numeric_column('passengers'),\n",
    "]\n",
    "\n",
    "def add_more_features(feats):\n",
    "  # Nothing to add (yet!)\n",
    "  return feats\n",
    "\n",
    "feature_cols = add_more_features(INPUT_COLUMNS)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h2> train_and_evaluate </h2>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def serving_input_fn():\n",
    "  feature_placeholders = {\n",
    "    'pickuplon' : tf.compat.v1.placeholder(tf.float32, [None]),\n",
    "    'pickuplat' : tf.compat.v1.placeholder(tf.float32, [None]),\n",
    "    'dropofflat' : tf.compat.v1.placeholder(tf.float32, [None]),\n",
    "    'dropofflon' : tf.compat.v1.placeholder(tf.float32, [None]),\n",
    "    'passengers' : tf.compat.v1.placeholder(tf.float32, [None]),\n",
    "  }\n",
    "  features = {\n",
    "      key: tf.expand_dims(tensor, -1)\n",
    "      for key, tensor in feature_placeholders.items()\n",
    "  }\n",
    "  return tf.estimator.export.ServingInputReceiver(features, feature_placeholders)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def train_and_evaluate(output_dir, num_train_steps):\n",
    "  estimator = tf.estimator.LinearRegressor(\n",
    "                       model_dir = output_dir,\n",
    "                       feature_columns = feature_cols)\n",
    "  train_spec=tf.estimator.TrainSpec(\n",
    "                       input_fn = read_dataset('./taxi-train.csv', mode = tf.estimator.ModeKeys.TRAIN),\n",
    "                       max_steps = num_train_steps)\n",
    "  exporter = tf.estimator.LatestExporter('exporter', serving_input_fn)\n",
    "  eval_spec=tf.estimator.EvalSpec(\n",
    "                       input_fn = read_dataset('./taxi-valid.csv', mode = tf.estimator.ModeKeys.EVAL),\n",
    "                       steps = None,\n",
    "                       start_delay_secs = 1, # start evaluating after N seconds\n",
    "                       throttle_secs = 10,  # evaluate every N seconds\n",
    "                       exporters = exporter)\n",
    "  tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Run training    \n",
    "OUTDIR = 'taxi_trained'\n",
    "shutil.rmtree(OUTDIR, ignore_errors = True) # start fresh each time\n",
    "train_and_evaluate(OUTDIR, num_train_steps = 5000)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Copyright 2021 Google Inc. Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
